package org.unt.mail.sender.other;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * @author Rafael
 */
public class MailSenderThread extends Thread {

    private static Logger logger = Logger.getLogger("mail");

    private static List<MessageBean> messages = new ArrayList<MessageBean>();

    public static void queueMessageToSend(MessageBean message) {
        messages.add(message);
    }

    public static int SleepMillis = 10000;

    public static boolean working = false;

    public void run() {
        iterate();
    }

    private synchronized void iterate() {

        logger.info("Mail sender thread started. (" + Thread.currentThread().getName() + ")");

        while (MailSenderThread.working) {

            try {

                Thread.sleep(MailSenderThread.SleepMillis);

                // PropertyConfigurator.configureAndWatch() destroy the context
                // logger and ThrowableUtil get null
                if (logger == null) {
                    continue;
                }

                if (messages == null) {
                    logger.error("messagesToSend is null. (" + Thread.currentThread().getName() + ")");
                    continue;
                } else if (messages.size() == 0) {
                    logger.debug("messagesToSend has no elements. (" + Thread.currentThread().getName() + ")");
                    continue;
                } else {
                    logger.info("messagesToSend has " + messages.size() + " mails to send. (" + Thread.currentThread().getName() + ")");
                }

                while (messages.size() > 0) {

                    MessageBean message = messages.get(0);
                    if (message.getAttachment() == null) {
                        MailSender.sendMail(message);
                    } else {
                        //MailSender.sendMail(message, message.getAttachment());
                    }

                    messages.remove(0);
                }

            } catch (InterruptedException e) {
                logger.error("Error sending mail. (" + Thread.currentThread().getName() + ")");
                // logger.error(ThrowableUtil.toString(e));
            }
        }

        // Signal to the initializer
        MailSenderThread.working = true;
    }
}
